import pygame

class GridRenderer:
    def __init__(self, grid_width=10, grid_height=10, cell_size=50):
        """初始化网格渲染器

        参数:
            grid_width (int): 网格宽度(单元格数量)
            grid_height (int): 网格高度(单元格数量)
            cell_size (int): 每个单元格的像素大小
        """
        self.grid_width = grid_width
        self.grid_height = grid_height
        self.cell_size = cell_size
        self.line_color = (100, 100, 100)  # 网格线颜色
        self.bg_color = (30, 30, 30)      # 背景颜色

    def calculate_grid_position(self, screen_width, screen_height):
        """计算网格在屏幕上的位置(居中显示)"""
        grid_pixel_width = self.grid_width * self.cell_size
        grid_pixel_height = self.grid_height * self.cell_size
        offset_x = (screen_width - grid_pixel_width) // 2
        offset_y = ((screen_height - grid_pixel_height) // 2) + 30  # 下移60px
        return offset_x, offset_y

    def render(self, screen):
        """渲染网格到指定surface"""
        screen.fill(self.bg_color)
        offset_x, offset_y = self.calculate_grid_position(
            screen.get_width(), screen.get_height()
        )

        # 绘制垂直线
        for x in range(self.grid_width + 1):
            pygame.draw.line(
                screen,
                self.line_color,
                (offset_x + x * self.cell_size, offset_y),
                (offset_x + x * self.cell_size, offset_y + self.grid_height * self.cell_size)
            )

        # 绘制水平线
        for y in range(self.grid_height + 1):
            pygame.draw.line(
                screen,
                self.line_color,
                (offset_x, offset_y + y * self.cell_size),
                (offset_x + self.grid_width * self.cell_size, offset_y + y * self.cell_size)
            )